package velocity;

import com.alibaba.fastjson.JSONObject;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class VelocityHello  {
    public static void main(String[] args) {
        new VelocityHello().outVelocity();
    }



    // 设置模板引擎输出结果
    public void outVelocity() {
        // 设置属性初始化Velocity
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
        ve.setProperty(Velocity.INPUT_ENCODING, "utf-8");
        ve.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
        ve.init();

        // 读取模板文件
        Template t = ve.getTemplate("vm/vo.vm");

        // 模板设置值(模拟数据库获取数据)
        VelocityContext vc = new VelocityContext();
        vc.put("name","名称字段");
        vc.put("tableName","table");
        vc.put("useLombok","false");

        List<JSONObject> columnJSONList = new ArrayList<>();
        JSONObject json = null;
        String columnType = "";
        String javaType = "";
        int i = 0;
        for (; i < 5; i++) {
            json = new JSONObject();
            json.put("fieldName","fieldName" + i);
            json.put("mothodName","FieldName" + i);
            columnType = i > 1 ? (i < 3 ? "data":"int") : "varchar";
            javaType = i > 1 ? (i < 3 ? "Data":"int") : "String";
            json.put("columnType",columnType);
            json.put("javaType",javaType);
            columnJSONList.add(json);
        }
        vc.put("tableList",columnJSONList);

        // 输出数据
        StringWriter sw = new StringWriter();
        t.merge(vc,sw);
        System.out.println(sw.toString());
    }



}
